package com.health.viewscontrols;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.blankj.utilcode.util.AdaptScreenUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.health.BuildConfig;
import com.health.R;
import com.health.UpdateVersion;
import com.health.adapter.DoctorAdapter;
import com.health.adapter.SSQAdapter;
import com.health.adapter.XZ_CZHospitalAdapter;
import com.health.db.FDbManager;
import com.health.httpbean.AppUpdateBean;
import com.health.httpbean.AppUpdateReqBean;
import com.health.httpbean.HttpConstant;
import com.health.tools.UpdateAppHelper;
import com.health.viewscontrols.settings.DataDownLoadMainActivity;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.BD_DD_AREA;
import com.health.tablebean.BD_ORGANIZE_EMPLOYEE;
import com.health.tablebean.BD_ORGANIZE_INSTITUTION;
import com.health.tools.DownLoadTools;
import com.health.tools.GetPostJTYS;
import com.health.tools.GlobalConts;
import com.health.tools.IDCardTool;
import com.health.tools.IDCardTool.IDCardConnectListener;
import com.health.tools.SPUtil;
import com.health.viewscontrols.settings.MainActivity_Menu_Settings_JTYS;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import rxhttp.RxHttp;

/**
 * 省市区行政规划主界面
 * 
 * @author nova
 */
public class ConfigActivity extends NovaPtActivity
		implements OnClickListener, OnItemSelectedListener, IDCardConnectListener {

	private static final int FLAG1 = 1;
	private static final int FLAG2 = 2;
	private static final int FLAG3 = 3;
	private static final int FLAG4 = 4;
	private static final int FLAG5 = 5;
	private final static String TAG = "ConfigActivity";
	private Button loginBtn;
	private Button exitBtn;
	/** 同步数据 */
	private Button btn_sync;
	// ----------行政区------------
	/** 1省 */
	private Spinner sp1;
	private List<BD_DD_AREA> lstData1 = new ArrayList<BD_DD_AREA>();
	private String code1 = "";
	private String str1 = "";
	/** 2市 */
	private Spinner sp2;
	private List<BD_DD_AREA> lstData2 = new ArrayList<BD_DD_AREA>();
	private String code2 = "";
	private String str2 = "";
	/** 3区 */
	private Spinner sp3;
	private List<BD_DD_AREA> lstData3 = new ArrayList<BD_DD_AREA>();
	private String code3 = "";
	private String str3 = "";
	/** 4街道 */
	private Spinner sp4;
	private List<BD_DD_AREA> lstData4 = new ArrayList<BD_DD_AREA>();
	private String code4 = "";
	private String str4 = "";
	private String name4 = "";
	/** 5办事处 */
	private Spinner sp5;
	private List<BD_DD_AREA> lstData5 = new ArrayList<BD_DD_AREA>();
	private String code5 = "";
	private String str_bsc = "";// 办事处
	private String str_bsc_name = "";
	/** 前五级机构编号 */
	private EditText etCode1;
	private String str_ssqno = "";// 省市区id
	// -----------------行政区end------------------
	// ------------机构及人员-----------------
	/** 4乡镇医院 */
	private Spinner sp01;
	private List<BD_ORGANIZE_INSTITUTION> lstData01 = new ArrayList<BD_ORGANIZE_INSTITUTION>();
	private String code01 = "";
	private String name01 = "";

	/** 5村庄医院 */
	private Spinner sp02;
	private List<BD_ORGANIZE_INSTITUTION> lstData02 = new ArrayList<BD_ORGANIZE_INSTITUTION>();
	private String code02 = "";
	private String name02 = "";

	/** 机构编号 */
	private EditText edJgId;
	private String str_QuId = "";// 行政区id

	/** 医生、村庄医院 、建档人 */
	private Spinner spDoc;
	private List<BD_ORGANIZE_EMPLOYEE> listDoc = new ArrayList<BD_ORGANIZE_EMPLOYEE>();
	private String docName = "";
	private String docId = "";
	private String docPassward = "";
	private String docUsername = "";
	private String docIDCard = "";
	// -------------机构及人员--------------

	/** 医生id */
	private EditText edDocId;
	/** 医生名称 */
	private TextView tvDocName;

	private List<BD_ORGANIZE_INSTITUTION> listCS_Hospital = new ArrayList<BD_ORGANIZE_INSTITUTION>();// 城市医院

	private TextView xinzhengqu;
	private ImageView img_settings;

	private TextView tv_no;

	public static String intent_str = "ConfigActivity";
	private int countResume = 0;
	private List<ARCHIVE_BASEINFO> isUpdate = new ArrayList<>();
	private FDbManager fdbmanger = null;



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.configoption2);
		findViews();
		setListeners();
		getPro(FLAG1, "0");

		String versionName = GlobalConts.getVerName(ConfigActivity.this);
		if (!TextUtils.isEmpty(versionName)) {
			tv_no.setText("V  "+ BuildConfig.VERSION_NAME);
		} else {
			tv_no.setText("");
		}

		try {
			if (GlobalConts.isNetworkAvailable(ConfigActivity.this)) {
				UpdateVersion up = new UpdateVersion(ConfigActivity.this);
				up.setSetDialogFlag(false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		WindowManager windowManager = getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		@SuppressWarnings("deprecation")
		int screenWidth = display.getWidth();
		@SuppressWarnings("deprecation")
		int screenHeight = display.getHeight();
		Log.w(TAG, "" + screenWidth + "*" + screenHeight);

		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		float width = dm.widthPixels * dm.density;
		float height = dm.heightPixels * dm.density;
		Log.w(TAG, "-----" + width + "*" + height);
		try {
			initIdCardTool();
		} catch (Exception e) {
			e.printStackTrace();
		}
		checkVersion();

		requestPermission2();
	}

	private void requestPermission2() {
//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
//			XXPermissions.with(this)
//					// 申请单个权限
//					.permission(
//							Manifest.permission.BLUETOOTH_SCAN,
//							Manifest.permission.BLUETOOTH_CONNECT
//					)
//					.request(new OnPermissionCallback() {
//
//						@Override
//						public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
//
//							Log.e(TAG, "onGranted: " );
//						}
//
//						@Override
//						public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
//
//							Log.e(TAG, "onDenied: " );
//						}
//					});
//		}

	}

	private void checkVersion() {
		AppUpdateReqBean appUpdateReqBean = new AppUpdateReqBean();
		appUpdateReqBean.setType(7);
		appUpdateReqBean.setApkCode(BuildConfig.VERSION_CODE);
		RxHttp.postJson(HttpConstant.queryNewApk)
				.addAll(GsonUtils.toJson(appUpdateReqBean))
				.asClass(AppUpdateBean.class)
				.subscribe(resultBean -> {
					if (resultBean.getApkInfo() != null) {
						UpdateAppHelper.downloadApk(this,resultBean.getApkInfo().getApkUrl(), resultBean.getApkInfo().getRemark());
					}
					Log.e("xiaoxin", "sendFollowTable: 11" );

				}, throwable -> {
					Log.e("xiaoxin", "sendFollowTable:22 " );
				});
	}
	private void initIdCardTool() {
		IDCardTool tool = null;
		if (NovaApplication.idCardTool == null) {
			tool = new IDCardTool(this);
			NovaApplication.idCardTool = tool;
		}
		NovaApplication.idCardTool.beginScan();
		NovaApplication.idCardTool.setListener(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	public void findViews() {
		loginBtn = (Button) findViewById(R.id.login_btn);
		xinzhengqu = (TextView) findViewById(R.id.titleText);
		btn_sync = (Button) findViewById(R.id.btn_sync);
		exitBtn = (Button) findViewById(R.id.exit_btn);
		sp1 = (Spinner) findViewById(R.id.nicespinner_p);
		sp2 = (Spinner) findViewById(R.id.nicespinner_c);
		sp3 = (Spinner) findViewById(R.id.nicespinner_n);
		sp4 = (Spinner) findViewById(R.id.nicespinner_jd);
		sp5 = (Spinner) findViewById(R.id.nicespinner_bsc);
		etCode1 = (EditText) findViewById(R.id.ed_encode);
		sp01 = (Spinner) findViewById(R.id.spinner_xz);
		sp02 = (Spinner) findViewById(R.id.spinner_cz);
		edJgId = (EditText) findViewById(R.id.ed_hospitalname);
		spDoc = (Spinner) findViewById(R.id.spinner_employee);
		edDocId = (EditText) findViewById(R.id.ed_userid);
		tvDocName = (TextView) findViewById(R.id.tv_username);
		SpannableStringBuilder style = new SpannableStringBuilder(getString(R.string.main_xzq));
		style.setSpan(new ForegroundColorSpan(Color.WHITE), 0, 3, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		// 设置指定位置文字的颜色
		style.setSpan(new ForegroundColorSpan(Color.RED), 3, 39, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		style.setSpan(new AbsoluteSizeSpan(50), 0, 3, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		style.setSpan(new AbsoluteSizeSpan(40), 34, 39, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		// 设置指定位置文字的大小
		style.setSpan(new AbsoluteSizeSpan(40), 3, 34, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		xinzhengqu.setText(style);
		img_settings = (ImageView) findViewById(R.id.img_settings);
		tv_no = (TextView) findViewById(R.id.tv_no);
		fdbmanger = NovaApplication.fdbmanger;
	}

	@Override
	public void setListeners() {
		loginBtn.setOnClickListener(this);
		sp1.setOnItemSelectedListener(this);
		sp2.setOnItemSelectedListener(this);
		sp3.setOnItemSelectedListener(this);
		sp4.setOnItemSelectedListener(this);
		sp5.setOnItemSelectedListener(this);
		sp02.setOnItemSelectedListener(this);
		sp01.setOnItemSelectedListener(this);
		spDoc.setOnItemSelectedListener(this);
		btn_sync.setOnClickListener(this);
		exitBtn.setOnClickListener(this);
		img_settings.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_btn:
			String docdw = "";
			String jddwno = "";
			if (code02.equals("")) {
				jddwno = code01;
				docdw = name01;
			} else {
				jddwno = code02;
				docdw = name02;
			}

			if (TextUtils.isEmpty(docName) || TextUtils.isEmpty(docId)) {
				showTextDialog("请选择机构及人员");
				return;
			}
			// 保存选中信息
			saveID(name4, str4, str_bsc_name, str_bsc, docdw, jddwno, docName, docId, str_ssqno.replace("-", ""),
					str_QuId.replace("-", ""), docPassward, str1, str2, str3, docUsername, docIDCard);
			Intent intent = new Intent(ConfigActivity.this, MainActivity_Menu_JTYS.class);
			intent.putExtra("from", "MainActivity_Login2");
			startActivity(intent);
			Log.e("adffsdfd",
					code01 + "=========" + code02 + "==========" + NovaApplication.getJgbh() + "===1"
							+ SPUtil.getstr_p(mContext) + "===2" + SPUtil.getstr_c(mContext) + "===3"
							+ SPUtil.getstr_n(mContext));
			break;
		case R.id.exit_btn:
			GlobalConts.exitApp(ConfigActivity.this);
			break;
		case R.id.btn_sync:
			// 同步数据
			// 设置行政区
			showSynDialog(ConfigActivity.this);
			break;
		case R.id.img_settings:
			Intent intent2 = new Intent(ConfigActivity.this, MainActivity_Menu_Settings_JTYS.class);
			startActivity(intent2);
			break;
		default:
			break;
		}
	}

	@SuppressLint("InflateParams")
	private void showSynDialog(final Context context) {
		final View textEntryView = LayoutInflater.from(this).inflate(R.layout.syn_dialog, null);
		final EditText ed_xzbh = (EditText) textEntryView.findViewById(R.id.ed_xzbh);
		ed_xzbh.setText(SPUtil.getstr_xzq(ConfigActivity.this));
		final EditText ed_pwd = (EditText) textEntryView.findViewById(R.id.ed_pwd);

		isUpdate = fdbmanger.findAllByWhere(ARCHIVE_BASEINFO.class, " IS_UPDATE= 'Y'");
		if (isUpdate.size() == 0) {
			// 选择是否上传
			new AlertDialog.Builder(ConfigActivity.this).setTitle("操作提示(是否更改?)")
					.setMessage("更改行政区之后，本地数据会被清空，请谨慎操作，是否更改？")
					.setPositiveButton("是", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int whichButton) {
							showXZQDialog(context, textEntryView, ed_xzbh, ed_pwd);
						}
					}).setNegativeButton("否", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					}).show();
		} else {
			new AlertDialog.Builder(ConfigActivity.this).setTitle("操作提示(是否上传?)")
					.setMessage(
							"1. 您有 " + isUpdate.size() + "条数据未上传 ,请先进行 数据上传 后再进行该操作 !\n" + "2. 更改行政区后数据将会被清空,请谨慎操作!")
					.setPositiveButton("是", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(ConfigActivity.this, DataDownLoadMainActivity.class);
							startActivity(intent);
						}
					}).setNegativeButton("否", new DialogInterface.OnClickListener() {
						// 同步数据
						@Override
						public void onClick(DialogInterface dialog, int which) {
							showXZQDialog(context, textEntryView, ed_xzbh, ed_pwd);
						}
					}).show();
		}
	}

	/**
	 * @param context
	 * @param textEntryView
	 * @param ed_xzbh
	 * @param ed_pwd
	 *            更改行政区
	 */
	public void showXZQDialog(final Context context, final View textEntryView, final EditText ed_xzbh,
			final EditText ed_pwd) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setCancelable(false);
		builder.setView(textEntryView);
		builder.setPositiveButton("同步", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				final String str_xzbh = ed_xzbh.getText().toString();
				if (TextUtils.isEmpty(str_xzbh) || str_xzbh.length() != 6) {
					showTextDialog("请输入正确的行政编号");
					return;
				}
				String str_pwd = ed_pwd.getText().toString();
				if (str_pwd.equals("nova8888")) {
					String fileURl = GlobalConts.getUrlPost() + GetPostJTYS.URL_DBSYNC + "?orgDistrictId=" + str_xzbh;
					if (!TextUtils.isEmpty(fileURl)) {
						SPUtil.setstr_xzq(ConfigActivity.this, str_xzbh);
						DownLoadTools downLoad = new DownLoadTools(ConfigActivity.this);
						downLoad.downloadFile(fileURl, NovaApplication.dbPath);
					}
				} else {
					showTextDialog("密码有误，请重新输入");
				}
			}
		});
		builder.setNegativeButton("取消", null);
		builder.show();
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		switch (parent.getId()) {
		case R.id.nicespinner_p:// 1
			str1 = lstData1.get(position).getGBCODE();
			lstData3 = new ArrayList<BD_DD_AREA>();
			getPro(FLAG2, str1);
			refRgIDText();
			str2 = "";
			break;
		case R.id.nicespinner_c:// 2
			str2 = lstData2.get(position).getGBCODE();
			getPro(FLAG3, str2);
			refRgIDText();
			str3 = "";
			str_QuId = "";
			break;
		case R.id.nicespinner_n:// 3
			str3 = lstData3.get(position).getGBCODE();
			str_QuId = lstData3.get(position).getGBCODE();
			getPro(FLAG4, str3);
			refRgIDText();
			break;
		case R.id.nicespinner_jd:// 4
			str4 = lstData4.get(position).getGBCODE();
			name4 = lstData4.get(position).getNAME();
			getPro(FLAG5, str4);
			refRgIDText();
			str_bsc = "";
			str_bsc_name = "";
			Log.e(TAG,"00000--str4:"+str4+"---name4:"+name4+"\n"+str_bsc+str_bsc_name);
			break;
		case R.id.nicespinner_bsc:// 5
			str_bsc = lstData5.get(position).getGBCODE();
			str_bsc_name = lstData5.get(position).getNAME();
			Log.e(TAG,"0000011111--str4:"+str4+"---name4:"+name4+"\n"+str_bsc+str_bsc_name);
			refRgIDText();
			break;
		case R.id.spinner_xz:// 6
			code02 = "";
			name02 = "";
			code01 = lstData01.get(position).getORGANCODE();
			name01 = lstData01.get(position).getORGANNAME();
			getCS_XZ_Hospital(2, code01);
			setDataTextView_Hospital();
			Log.e(TAG,"机构名称："+name01);
			break;
		case R.id.spinner_cz:// 7
			code02 = lstData02.get(position).getORGANCODE();
			name02 = lstData02.get(position).getORGANNAME();
			int selectedItemPosition = sp02.getSelectedItemPosition();
			if (0== selectedItemPosition) {
				code02 = "";
			}
			setDataTextView_Hospital();
			docName = "";
			docId = "";
			docPassward = "";
			docIDCard = "";
			edDocId.setText("");

			docUsername = "";
			tvDocName.setText("");

			break;
		case R.id.spinner_employee:// doc
			docName = listDoc.get(position).getNAME();
			docId = listDoc.get(position).getUSER_ID();
			docPassward = listDoc.get(position).getPASSWORD();
			docIDCard = listDoc.get(position).getIDCARD();
			edDocId.setText(docId);
			docUsername = listDoc.get(position).getUSER_NAME();
			NovaApplication.setDoctorGbcode(listDoc.get(position).getGBCODE());
			Log.e("---", docName + docId + docPassward + docIDCard + docUsername);
			tvDocName.setText("登录账号：" + docUsername);
			break;
		default:
			break;
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}

	/**
	 * flag 1省 2市 3区/县 4乡镇 5 街道
	 * 
	 * @param flag
	 * @param dlevel
	 * @author 王婷婷
	 * @date 2015年12月8日 上午11:55:03
	 */
	private void getPro(int flag, String dlevel) {
		try {
			if (!TextUtils.isEmpty(NovaApplication.getXzqhNo())) {
				switch (flag) {
				case FLAG1:
					lstData1 = NovaApplication.fdbmanger.findAllByWhere(BD_DD_AREA.class, "DLEVEL='" + dlevel
							+ "' and GBCODE like '" + NovaApplication.getXzqhNo().substring(0, 2) + "%'");
					break;
				case FLAG2:
					lstData2 = NovaApplication.fdbmanger.findAllByWhere(BD_DD_AREA.class, "DLEVEL='" + dlevel
							+ "' and GBCODE like '" + NovaApplication.getXzqhNo().substring(0, 4) + "%'");
					break;
				case FLAG3:
					lstData3 = NovaApplication.fdbmanger.findAllByWhere(BD_DD_AREA.class,
							"DLEVEL='" + dlevel + "' and GBCODE like '" + NovaApplication.getXzqhNo() + "%'");
					break;
				case FLAG4:
					lstData4 = NovaApplication.fdbmanger.findAllByWhere(BD_DD_AREA.class, "DLEVEL='" + dlevel + "'");
					break;
				case FLAG5:
					lstData5 = NovaApplication.fdbmanger.findAllByWhere(BD_DD_AREA.class, "DLEVEL='" + dlevel + "'");
					break;
				default:
					break;
				}
			}
			bindSpinner(flag);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 行政区BindSpinner
	 */
	public void bindSpinner(int flag) {
		switch (flag) {
		case FLAG1:
			ss(sp1, code1, lstData1);
			sp1.setOnItemSelectedListener(this);
			break;
		case FLAG2:
			ss(sp2, code2, lstData2);
			sp2.setOnItemSelectedListener(this);
			break;
		case FLAG3:
			ss(sp3, code3, lstData3);
			getCS_XZ_Hospital(0, str2);
			break;
		case FLAG4:
			ss(sp4, code4, lstData4);
			break;
		case FLAG5:
			ss(sp5, code5, lstData5);
			break;
		default:
			break;
		}
	}

	/**
	 * 判断当前城市在数组中的位置并显示
	 * 
	 * @author 鹿云龙
	 * @date 2017年12月19日 下午1:38:17
	 */
	private void ss(Spinner sp, String code, List<BD_DD_AREA> bds) {

		int flagIndex3 = -1;
		if (!code.equals("")) {
			int length = bds.size();
			if (length > 0) {
				for (int i = 0; i < length; i++) {
					if (bds.get(i).getGBCODE().equals(code)) {
						flagIndex3 = i;
					}
				}
			} else {
				bds = new ArrayList<>();
			}
		}
		SSQAdapter adapter_n = new SSQAdapter(getApplicationContext(), bds);
		// adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp.setAdapter(adapter_n);
		if (flagIndex3 != -1) {
			sp.setSelection(flagIndex3);
			code = "";
		}
	}

	/**
	 * 设置文本内容
	 * 
	 * 刷新省市机构id文本框
	 * 
	 * @author 王婷婷
	 * @date 2015年12月8日 下午4:19:34
	 */
	private void refRgIDText() {
		str_ssqno = str1 + "-" + str2.replace(str1, "") + "-" + str3.replace(str2, "") + "-" + str4.replace(str3, "")
				+ "-" + str_bsc.replace(str4, "");
		etCode1.setText(str_ssqno);
	}

	/**
	 * 设置省市区编号
	 * 
	 * @author 王婷婷
	 * @date 2015年12月8日 下午4:19:34
	 */
	private void setDataTextView_Hospital() {
		if ("".equals(code02)) {
			edJgId.setText(code01);
			initDoc(code01);
		} else {
			edJgId.setText(code02);
			initDoc(code02);
		}
	}

	/**
	 * 获取城市乡镇医院 flag 0城市 1乡镇 2城市
	 * 
	 * @param flag
	 * @author 王婷婷
	 * @date 2015年12月8日 上午11:55:03
	 */
	private void getCS_XZ_Hospital(int flag, String parentId) {
		try {
			Log.e("获取城市乡镇医院", flag + "\n" + parentId);
			List<BD_ORGANIZE_INSTITUTION> bd_ORGANIZE_INSTITUTIONAs = NovaApplication.fdbmanger
					.findAllByWhere(BD_ORGANIZE_INSTITUTION.class, "PARENTID='" + parentId + "'");
			Log.e("List", bd_ORGANIZE_INSTITUTIONAs.size() + "");
			int pLength = bd_ORGANIZE_INSTITUTIONAs.size();
			if (pLength > 0) {
				if (flag == 0) {
					listCS_Hospital = bd_ORGANIZE_INSTITUTIONAs;
					getCS_XZ_Hospital(1, listCS_Hospital.get(0).getORGANCODE());
				} else {
					bindSpinner_CS_XZ_Hospital(flag, bd_ORGANIZE_INSTITUTIONAs);
				}
			} else {
				listCS_Hospital = new ArrayList<>();
				bindSpinner_CS_XZ_Hospital(flag, bd_ORGANIZE_INSTITUTIONAs);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 判断当前乡镇在数组中的位置并显示
	public void bindSpinner_CS_XZ_Hospital(int flag, List<BD_ORGANIZE_INSTITUTION> bds) {
		if (flag == 1) {
			lstData01 = bds;
			int flagIndex1 = -1;
			Log.e(TAG,"bindSpinner_CS_XZ_Hospital");
			for(BD_ORGANIZE_INSTITUTION info:lstData01){
				Log.e(TAG,"数据："+info.getADDRESS());
			}

			XZ_CZHospitalAdapter adapter_p = new XZ_CZHospitalAdapter(getApplicationContext(), lstData01);
			sp01.setAdapter(adapter_p);
			if (flagIndex1 != -1) {
				sp01.setSelection(flagIndex1);
			}
			sp01.setOnItemSelectedListener(this);
		} else if (flag == 2) {
			lstData02 = bds;

			List<BD_ORGANIZE_INSTITUTION> list = new ArrayList<>();
			list = lstData02;
			BD_ORGANIZE_INSTITUTION bd = new BD_ORGANIZE_INSTITUTION();
			bd.setORGANNAME("请选择");
			list.add(0, bd);

			int flagIndex2 = -1;
			XZ_CZHospitalAdapter adapter = new XZ_CZHospitalAdapter(getApplicationContext(), list);
			sp02.setAdapter(adapter);
			if (flagIndex2 != -1) {
				sp02.setSelection(flagIndex2);
			}
			sp02.setOnItemSelectedListener(this);

		}
	}

	/**
	 * 本地缓存医生列表并绑定医生SPinner
	 * 
	 * @param parentId
	 * @author 王婷婷
	 * @date 2015年12月9日 下午4:00:35
	 */
	private void initDoc(String parentId) {
		try {
			listDoc = NovaApplication.fdbmanger.findAllByWhere(BD_ORGANIZE_EMPLOYEE.class,
					"ORGANCODE='" + parentId + "'");
			int pLength = listDoc.size();
			if (pLength > 0) {
				NovaApplication.setDoctorList(listDoc);// 医生列表赋值
			} else {
			}
			bindSpinner_Doctors();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 绑定医生列表
	 * 
	 * @author 王婷婷
	 * @date 2015年12月9日 下午3:30:40
	 */
	public void bindSpinner_Doctors() {
		// 判断当前乡镇在数组中的位置并显示
		DoctorAdapter adapter_p = new DoctorAdapter(getApplicationContext(), listDoc);
		spDoc.setAdapter(adapter_p);
		spDoc.setOnItemSelectedListener(this);
	}

	/**
	 * 保存数据信息 no 为对应的编号
	 * 
	 * @param str_xz  (行政区 4级)
	 *            乡镇
	 * @param str_cz (行政区 5级)
	 *            村庄
	 * @param str_jddw （ 当前机构）
	 *            建档单位
	 * @param str_jdr （建档人）
	 *            建档人
	 *            建档人编号 str_ssqno 省市区编号----对应 个人档案编号 str_jdpassward 密码 str_xzq
	 *            行政区编号【用于更新数据库】
	 * @author 王婷婷
	 * @date 2015年12月10日 下午3:41:38
	 */
	private void saveID(String str_xz, String str_xzno, String str_cz, String str_czno, String str_jddw,
			String str_jddwno, String str_jdr, String str_jdrno, String str_ssqno, String str_xzq,
			String str_jdpassward, String str_p, String str_c, String str_n, String str_jdrusername,
			String str_jdrIDCard) {
		SharedPreferences sp = getSharedPreferences(SPUtil.SP_NAME, 0);
		sp.edit().putString(SPUtil.STR_XZ, str_xz).putString(SPUtil.STR_XZNO, str_xzno).putString(SPUtil.STR_CZ, str_cz)
				.putString(SPUtil.STR_CZNO, str_czno).putString(SPUtil.STR_JDDW, str_jddw)
				.putString(SPUtil.STR_JDDWNO, str_jddwno).putString(SPUtil.STR_JDR, str_jdr)
				.putString(SPUtil.STR_JDRNO, str_jdrno).putString(SPUtil.STR_SSQNO, str_ssqno)
				.putString(SPUtil.STR_XZQ, str_xzq).putString(SPUtil.STR_JDPADDWARD, str_jdpassward)
				.putString(SPUtil.STR_P, str_p).putString(SPUtil.STR_C, str_c).putString(SPUtil.STR_N, str_n)
				.putString(SPUtil.STR_JDRUSERNAME, str_jdrusername).putString(SPUtil.STR_JDRIDCARD, str_jdrIDCard)
				.commit();
		Log.e(TAG,"imei:"+ SPUtil.getRegisterImei(ConfigActivity.this));
		Log.e(TAG,"docdw:"+str_jddw+"jddwno:"+str_jddwno+"\n"+SPUtil.getstr_jddw(ConfigActivity.this)+SPUtil.getStrjddwno(ConfigActivity.this));
		Log.e(TAG,"STR_XZ:"+SPUtil.getstr_xz(ConfigActivity.this)+"STR_XZNO:"+SPUtil.getstr_xzno(ConfigActivity.this)
				+"\n"+SPUtil.getstr_czno(ConfigActivity.this)+SPUtil.getstr_cz(ConfigActivity.this));
	}

	public void clearID() {
		// 获得SharedPreferences对象
		// 保存组件中的值
		SPUtil.setstr_xz(ConfigActivity.this, "");
		SPUtil.setstr_xzno(ConfigActivity.this, "");
		SPUtil.setstr_cz(ConfigActivity.this, "");
		SPUtil.setstr_czno(ConfigActivity.this, "");
		SPUtil.setstr_jddw(ConfigActivity.this, "");
		SPUtil.setStrjddwno(ConfigActivity.this, "");
		SPUtil.setstr_jdr(ConfigActivity.this, "");
		SPUtil.setStr_jdrno(ConfigActivity.this, "");
		SPUtil.setstr_ssqno(ConfigActivity.this, "");
		SPUtil.setstr_xzq(ConfigActivity.this, "");
		SPUtil.setstr_jdpassward(ConfigActivity.this, "");
		SPUtil.setstr_p(ConfigActivity.this, "");
		SPUtil.setstr_c(ConfigActivity.this, "");
		SPUtil.setstr_n(ConfigActivity.this, "");
		SPUtil.setstr_jdrusername(ConfigActivity.this, "");
	}

	@SuppressWarnings("unused")
	private int getDataFromSdCard() {
		int size = 0;
		try {
			// 数据库名称。
			String SQL_NAME = android.os.Environment.getExternalStorageDirectory().getAbsolutePath()
					+ GlobalConts.TYPE_DBFILENAME + "/EhrApp.db";
			String mainDataSQL = "select * from  ARCHIVE_BASEINFO";
			File name = new File(SQL_NAME);
			// 读SD卡数据库必须如此--用静态方法打开数据库。
			SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(name, null);
			Cursor cursor = db.rawQuery(mainDataSQL, null);
			List<ARCHIVE_BASEINFO> dataList = new ArrayList<ARCHIVE_BASEINFO>();
			if (cursor != null) {
				// 直到返回false说明表中到了数据末尾
				while (cursor.moveToNext()) {
					ARCHIVE_BASEINFO data = new ARCHIVE_BASEINFO();
					dataList.add(data);
				}
				size = dataList.size();
			}
			cursor.close();
			db.close();
		} catch (Exception e) {
			size = -1;
			e.printStackTrace();
		}
		return size;
	}

	@Override
	public void onIDCardConnect() {

	}

	@Override
	public void onIDDataReceived(String data) {

	}

	/**
	 * 返回事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			GlobalConts.exitApp(ConfigActivity.this);
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onResume() {
		super.onResume();
		countResume++;
		if (countResume == 0) {
		} else {
			if (NovaApplication.idCardTool != null) {
				if (!IDCardTool.isConnectSocket) {
					Log.e(TAG, "NovaApplication.idCardTool.isConnectSocket==" + IDCardTool.isConnectSocket);
					NovaApplication.idCardTool.closeAndExit();
					initIdCardTool();
				}
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (NovaApplication.idCardTool != null) {
			NovaApplication.idCardTool.closeAndExit();
		}
		NovaApplication.idCardTool = null;
	}
}